#-*- coding:utf-8 -*-

'''
    功能函数
'''
from hashlib import md5
from datetime import datetime
from setting import CRYPT_STR

def encrypt(md5string):
    '''
    使用MD5加密字符串,并返回加密后的字符串
    '''
    hash_md5 = md5(md5string+CRYPT_STR)
    md5_data = hash_md5.hexdigest()
    return md5_data



def get_shell(user, passwd):
    return encrypt(user + encrypt(passwd))




def not_empty(*args):
    '''
    测试参数不允许为空
    '''
    for arg in args:
	if not all(args):
	    raise ValueError("Arguments are not allowed emtpy")



def get_cate(cate):
    if type(cate) == list:
	return cate
    else:
	_cate = []
	if cate:
	    for c in cate.split(','):
		_cate.append(c)
	    else:
		_cate = ['未分类']

	return _cate

        
# 获取id
def getLastId(db, coll):
    '''
    mongodb 不支持自增id用自己的程序来自增
    '''
    # 查看集合是否为空
    if db[coll].find_one():
        for rows in db[coll].find().sort("id", DESCENDING).limit(1):
            rid = int(rows["id"]) + 1
    else:
        rid = 1
    return rid






def get_subdate(year, month):
    '''
    根据年月获取这个月的起点和终点
    param:
    `year`(int):
    `month`(int):
    return : (start, end):datetime
    '''
   
    year = int(year)
    month = int(month)
    
    if (month + 1) > 12:
        nyear = year + 1
        nmonth = 1
    else:
        nyear = year
        nmonth = month + 1

    start = datetime(year, month, 1)
    end = datetime(nyear, nmonth, 1)
    return start, end
